package com.flycms.modules.group.controller.manage;

import com.flycms.common.constant.UserConstants;
import com.flycms.common.utils.DateUtils;
import com.flycms.common.utils.StrUtils;
import com.flycms.common.utils.page.Pager;
import com.flycms.common.validator.Order;
import com.flycms.common.validator.Sort;
import com.flycms.modules.elastic.service.IElasticSearchService;
import com.flycms.modules.group.domain.GroupTopicRecommend;
import com.flycms.modules.group.domain.dto.AdminGroupTopicDTO;
import com.flycms.modules.group.domain.vo.GroupTopicVO;
import com.flycms.modules.group.service.IGroupTopicRecommendService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.flycms.framework.aspectj.lang.annotation.Log;
import com.flycms.framework.aspectj.lang.enums.BusinessType;
import com.flycms.modules.group.domain.GroupTopic;
import com.flycms.modules.group.domain.dto.GroupTopicDTO;
import com.flycms.modules.group.service.IGroupTopicService;
import com.flycms.framework.web.controller.BaseController;
import com.flycms.framework.web.domain.AjaxResult;
import com.flycms.common.utils.poi.ExcelUtil;
import com.flycms.framework.web.page.TableDataInfo;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 小组话题Controller
 * 
 * @author admin
 * @date 2020-09-27
 */
@RestController
@RequestMapping("/system/group/topic")
public class GroupTopicAdminController extends BaseController
{
    @Autowired
    private IGroupTopicService groupTopicService;
    @Autowired
    private IElasticSearchService elasticSearchService;
    @Autowired
    private IGroupTopicRecommendService groupTopicRecommendService;

    /////////////////////////////////
    ///////       增加       ////////
    /////////////////////////////////


    /////////////////////////////////
    ///////        刪除      ////////
    /////////////////////////////////
    /**
     * 删除小组话题
     */
    @PreAuthorize("@ss.hasPermi('group:topic:remove')")
    @Log(title = "小组话题", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        if(!StrUtils.isEmpty(ids)){
            for (long id :ids){
                elasticSearchService.deleteDocument("topic",String.valueOf(id));
            }
        }
        return toAjax(groupTopicService.deleteGroupTopicByIds(ids));
    }


    /////////////////////////////////
    ///////        修改      ////////
    /////////////////////////////////
    /**
     * 修改小组话题
     */
    @PreAuthorize("@ss.hasPermi('group:topic:edit')")
    @Log(title = "小组话题", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody GroupTopicVO topicVo)
    {
        GroupTopicDTO topic= groupTopicService.findGroupTopicById(Long.valueOf(topicVo.getId()));
        if(topic == null){
            return AjaxResult.error("话题不存在");
        }

        if (UserConstants.NOT_UNIQUE.equals(groupTopicService.checkGroupTopicNameUnique(topicVo)))
        {
            return AjaxResult.error("该用户已有相同标题内容！");
        }

        //添加推荐设置
        if(topicVo.getRecommends()!=null && topicVo.getRecommends().length > 0){
            groupTopicRecommendService.deleteGroupTopicRecommendByContentId(0,Long.valueOf(topicVo.getId()));
            Arrays.asList(topicVo.getRecommends()).stream().forEach(x -> {
                GroupTopicRecommend recommend = new GroupTopicRecommend();
                recommend.setContentId(Long.valueOf(topicVo.getId()));
                recommend.setRecommend(Integer.parseInt(x));
                recommend.setGroupId(Long.valueOf(topicVo.getGroupId()));
                groupTopicRecommendService.insertGroupTopicRecommend(recommend);
            });
        }

        return groupTopicService.updateGroupTopic(topicVo);
    }


    /////////////////////////////////
    ///////        查詢      ////////
    /////////////////////////////////
    /**
     * 查询小组话题列表
     */
    @PreAuthorize("@ss.hasPermi('group:topic:list')")
    @GetMapping("/list")
    public TableDataInfo list(GroupTopic groupTopic,
        @RequestParam(defaultValue = "1") Integer pageNum,
        @RequestParam(defaultValue = "10") Integer pageSize,
        @Sort @RequestParam(defaultValue = "create_time") String sort,
        @Order @RequestParam(defaultValue = "desc") String order)
    {
        Pager<GroupTopicDTO> pager = groupTopicService.selectGroupTopicPager(groupTopic, pageNum, pageSize, sort, order);
        return getDataTable(pager.getList(),pager.getTotal());
    }

    /**
     * 导出小组话题列表
     */
    @PreAuthorize("@ss.hasPermi('group:topic:export')")
    @Log(title = "小组话题", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export()
    {
        List<GroupTopicDTO> topic = groupTopicService.selectGroupTopicAllList();
        ExcelUtil<GroupTopicDTO> util = new ExcelUtil<GroupTopicDTO>(GroupTopicDTO.class);
        return util.exportExcel(topic, "小组话题");
    }

    /**
     * 获取小组话题详细信息
     */
    @PreAuthorize("@ss.hasPermi('group:topic:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        GroupTopicDTO topic=groupTopicService.findGroupTopicById(id);
        AdminGroupTopicDTO dto = new AdminGroupTopicDTO();
        dto.setId(topic.getId());
        dto.setColumnId(topic.getColumnId());
        dto.setColumnName(topic.getColumnName());
        dto.setGroupId(topic.getGroupId());
        dto.setGroupName(topic.getGroupName());
        dto.setTitle(topic.getTitle());
        dto.setUserId(topic.getUserId());
        dto.setIstop(topic.getIstop());
        dto.setIsclose(topic.getIsclose());
        dto.setIscomment(topic.getIscomment());
        dto.setIscommentshow(topic.getIscommentshow());
        dto.setIsposts(topic.getIsposts());
        String[] recommends=groupTopicRecommendService.findGroupTopicRecommendById(null,null,topic.getId());
        if(recommends !=null){
            dto.setRecommends(recommends);
        }
        dto.setStatus(topic.getStatus());
        return AjaxResult.success(dto);
    }

    /**
     * 获取同义词词库详细信息
     */
    @PreAuthorize("@ss.hasPermi('group:topic:query')")
    @GetMapping(value = "/all-index")
    public AjaxResult allIndex() throws Exception {
        if (elasticSearchService.instance() != null) {
            elasticSearchService.deleteAllIndex();
            GroupTopic entity = new GroupTopic();
            entity.setIsaudit("2");
            entity.setDeleted("0");
            entity.setStatus("2");

            int topicCount=groupTopicService.queryGroupTopicTotal(entity);
            int c = topicCount%1000==0?topicCount/1000:topicCount/1000+1;
            for (int i=0; i<c;i++) {
                Pager<GroupTopicDTO> pager = groupTopicService.selectGroupTopicPager(entity, i, 1000, null, null);
                Map<String, Map<String, Object>> sources = pager.getList().stream().collect(Collectors.toMap(key -> String.valueOf(key
                        .getId()), value -> {
                    Map<String, Object> map = new HashMap<>();
                    map.put("infoType", "1");
                    map.put("groupId", String.valueOf(value.getGroupId()));
                    map.put("columnId", String.valueOf(value.getColumnId()));
                    map.put("userId", String.valueOf(value.getUserId()));
                    map.put("title", value.getTitle());
                    map.put("content", StrUtils.trimHtml2Txt(value.getContent()));
                    String timeZoneConvert = DateUtils.timeZoneConvert(value.getCreateTime().getTime(), "yyyy-MM-dd'T'HH:mm:ss.SSSZ","Asia/Shanghai");
                    map.put("createTime", timeZoneConvert);
                    return map;
                }));
                elasticSearchService.bulkDocument("topic", sources);
            }
            return AjaxResult.success("更新成功");
        }
        return AjaxResult.error("更新失败");
    }
}
